Skip to content

docs(billing/crons): jitter & sharding guidance#3579

Merged
PierreBrisorgueil merged 4 commits into
masterfrom
docs/billing-cron-jitter-guidance
May 2, 2026
Merged

docs(billing/crons): jitter & sharding guidance#3579
PierreBrisorgueil merged 4 commits into
masterfrom
docs/billing-cron-jitter-guidance

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented May 2, 2026

Summary

  • Adds a Jitter & sharding section to modules/billing/crons/README.md, inserted after the Kubernetes CronJob example and before the meterMode dependency section.
  • Documents the recommended startup-jitter pattern, when-to-shard heuristic (>10k tenants or single-table contention), and constraints around idempotency window vs jitter window.
  • Clarifies that the cron.schedule snippet is illustrative (no node-cron dep in devkit).

Devkit-shipped crons run identical UTC schedules across all consumer deployments — without jitter, N consumers fan-in to one DB burst. This is documentation-only guidance; no code changes.

Test plan

  • CI green
  • Markdown renders correctly on GitHub preview

Summary by CodeRabbit

  • Documentation
    • Updated billing infrastructure documentation with guidance on performance optimization and system reliability for scheduled operations.

Copilot AI review requested due to automatic review settings May 2, 2026 18:24
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 2, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 45 minutes and 30 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 78a2b9c3-f5d6-4cda-b169-1dfaa56bc08f

📥 Commits

Reviewing files that changed from the base of the PR and between bbcf19e and 2013d78.

📒 Files selected for processing (1)
  • modules/billing/crons/README.md

Walkthrough

Documentation added to the billing crons module describing jitter and sharding strategies to mitigate thundering-herd effects. Covers startup jitter implementation, sharding criteria (tenant count threshold, single-table contention), example patterns, and constraints on jitter magnitude and applicability.

Changes

Cron Operational Guidance

Layer / File(s) Summary
Documentation
modules/billing/crons/README.md
New "Jitter & sharding" section (lines 56–83) explains startup jitter techniques with a setTimeout example, sharding triggers (>10k tenants or concurrency-sensitive tables), example scheduling patterns using organizationId modulo sharding or per-tenant queues, jitter magnitude constraints relative to idempotency windows, and a note to exclude SLA-critical jobs from jitter.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The pull request description covers the Summary section adequately but lacks complete coverage of the required template sections (Scope, Validation, Guardrails check, and Notes for reviewers). Expand the description to include Scope (modules impacted, cross-module impact, risk level), Validation checklist items, Guardrails checks, and Notes for reviewers to align with the repository template.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'docs(billing/crons): jitter & sharding guidance' is clear, concise, and directly summarizes the main change—adding documentation on jitter and sharding patterns to the billing crons module.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch docs/billing-cron-jitter-guidance

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 45 minutes and 30 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@codacy-production
Copy link
Copy Markdown

codacy-production Bot commented May 2, 2026

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@modules/billing/crons/README.md`:
- Around line 62-70: The README snippet claims jitter is "persisted across
restarts" but the example computes jitter with Math.random() on process start
(jitterMs) which re-randomizes on every restart; update the doc so the code and
text match by either (A) changing the prose to state the jitter is re-randomized
each restart, or (B) replace the Math.random() example with a
deterministic/persisted jitter derivation (e.g., derive jitterMs from a stable
pod identity like process.env.HOSTNAME via a small stable hash) and keep the
rest of the example using cron.schedule and BillingResetService.resetAllDue;
ensure you reference jitterMs, cron.schedule and BillingResetService.resetAllDue
in the updated snippet so readers can locate the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 22f28da3-ca1f-4781-b916-a0ad73177214

📥 Commits

Reviewing files that changed from the base of the PR and between 37d5679 and bbcf19e.

📒 Files selected for processing (1)
  • modules/billing/crons/README.md

Comment thread modules/billing/crons/README.md Outdated
Copy link
Copy Markdown

@codacy-production codacy-production Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

While this PR meets basic quality standards, there are significant architectural conflicts in the documentation that should be resolved before merging. The primary concern is the suggestion to use an internal application scheduler (cron.schedule) inside a script intended for execution by an external orchestrator like Kubernetes. This creates a risk of hung processes or missed executions.

Additionally, the documentation contains a technical inaccuracy regarding jitter persistence. In the ephemeral context of Kubernetes CronJobs, the provided code will not persist jitter across restarts. Refinement of these examples is necessary to provide safe and actionable guidance for production systems.

About this PR

  • There is a systemic inconsistency between the deployment model (external K8s CronJob) and the implementation examples (internal Node.js scheduler). The documentation should consistently promote patterns suitable for ephemeral, orchestrator-triggered tasks.

Test suggestions

  • Verify that the suggested jitter logic (setTimeout) does not exceed the documented idempotency window constraints.
  • Verify that sharding guidance provides specific actionable thresholds (e.g., 10k tenants).

TIP Improve review quality by adding custom instructions
TIP How was this review? Give us feedback

Comment thread modules/billing/crons/README.md Outdated
Comment thread modules/billing/crons/README.md Outdated
Comment thread modules/billing/crons/README.md
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds operational guidance to the billing cron documentation, explaining how downstream consumers can reduce burst load when running the module’s standalone billing cron scripts across many deployments. It fits the codebase by extending the billing module’s CronJob-oriented README without changing runtime behavior.

Changes:

  • Adds a new Jitter & sharding section to the billing cron README.
  • Documents a startup-jitter example, a heuristic for when to shard work, and constraints around jitter windows.
  • Clarifies that the scheduler snippet is illustrative and that billing crons are otherwise documented as Kubernetes CronJobs.

Comment thread modules/billing/crons/README.md Outdated
Comment thread modules/billing/crons/README.md Outdated
- Remove misleading "persisted across restarts" prose — K8s CronJob scripts
  are invoked once per execution, so jitter is naturally per-invocation
- Replace cron.schedule() snippet (no-cron-dep model) with a self-executing
  top-level await delay pattern matching the actual entrypoint structure
- Add optional stable per-pod jitter derivation from HOSTNAME hash
- Add SHARD_INDEX/SHARD_TOTAL env-var example in CronJob manifest + script
  filter snippet to complete sharding implementation guidance
…e hash

$where executes JS in MongoDB and is deprecated/disabled in newer versions.
Replace with a client-side hash on _id strings — same O(n) complexity, no
server-side JS dependency.
…lability note

- Wrap jitter snippet in async IIFE (CJS entrypoints don't support top-level await)
- Rename stable-jitter variables (hostHash/stableJitterMs) to avoid const redeclaration
  if both snippets appear in the same file
- Add scalability caveat on in-memory shard filter; point toward server-side $mod for
  high tenant counts
@PierreBrisorgueil PierreBrisorgueil merged commit 00ea494 into master May 2, 2026
3 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the docs/billing-cron-jitter-guidance branch May 2, 2026 18:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants